package com.agileai.portal.controller.base;

import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.DispatchRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.driver.model.LayoutContainer;
import com.agileai.portal.driver.model.Page;

public class ContainerWidthSetupHandler extends BaseHandler{
	public static final String CONTAINER_STYLE = "containerStyle";
	public static final String CONTAINER_TYPE = "containerType";
	public ContainerWidthSetupHandler(){
		super();
	}
	public ViewRenderer prepareDisplay(DataParam param) {
		this.setAttributes(param);
		Page page = (Page)this.getSessionAttribute(LayoutManageHandler.PAGE_SESSION_KEY);
		LayoutManageHandler layoutManageHandler = new LayoutManageHandler();
		layoutManageHandler.setRequest(this.request);
		String containerId = param.get(LayoutManageHandler.CONTAINER_ID);
		LayoutContainer curLayoutContainer = layoutManageHandler.retrieveLayoutContainer(containerId);
		String containerType = curLayoutContainer.getContainerType();
		if (LayoutContainer.ContainerType.COLUMN.equals(containerType)){
			LayoutContainer parentContainer = curLayoutContainer.getParentContainer();
			List<LayoutContainer> childList = null;
			if (parentContainer != null){
				childList = parentContainer.getChildContainerList();
			}else{
				childList = page.getLayoutContainers();
			}
			int childSize = childList.size();
			StringBuffer text = new StringBuffer();
			for (int i=0;i < childSize;i++){
				LayoutContainer tempLayoutContainer = childList.get(i);
				String width = tempLayoutContainer.getWidth();
				String tempWidth = width.substring(0,width.length()-1);
				if (containerId.equals(tempLayoutContainer.getId())){
					text.append("<input style='background-color:#F00' id='childWidth").append(i).append("' name='childWidth").append(i).append("' type='text' value='").append(tempWidth).append("' size='2' class='text' />");				
				}
				else{
					text.append("<input id='childWidth").append(i).append("' name='childWidth").append(i).append("' type='text' value='").append(tempWidth).append("' size='2' class='text' />");
				}
				text.append("%");
				if (i < childSize-1){
					text.append("--");	
				}
			}
			this.setAttribute("childSize", String.valueOf(childSize));
			this.setAttribute("widthHtml", text.toString());
		}
		this.setAttribute(CONTAINER_TYPE, containerType);
		this.setAttribute(CONTAINER_STYLE, curLayoutContainer.getStyle());
		return new LocalRenderer(getPage());
	}	
	public ViewRenderer doSetupWidthAction(DataParam param){
		String handlerURL = this.getHandlerURL(LayoutManageHandler.class);
		handlerURL = handlerURL+"&"+BaseHandler.ACTION_TYPE+"=setupWidth";
		return new DispatchRenderer(handlerURL);
	}	
}
